<?php
namespace Api\Controller;
use Think\Controller;
class IndexController extends Controller {
	// private $appkey; // = '64d79b64a17a7f0b0781421533fca4c0';
	private $AppKey;                //开发者平台分配的AppKey
    private $AppSecret;             //开发者平台分配的AppSecret,可刷新
    private $Nonce;                    //随机数（最大长度128个字符）
    private $CurTime;              //当前UTC时间戳，从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
    private $CheckSum;             //SHA1(AppSecret + Nonce + CurTime),三个参数拼接的字符串，进行SHA1哈希计算，转化成16进制字符(String，小写)

	public function __construct()
	{
		$this->AppKey = '64d79b64a17a7f0b0781421533fca4c0';
		// $this->Nonce = $this->getNonceStr();
		// $this->CurTime = time();
	}


    public function index(){
    	$this->checkSumBuilder();
        $url = 'https://api.netease.im/nimserver/user/create.action';
        
        $http_header = array(
            'AppKey:'. $this->AppKey,
            'Nonce:'. $this->Nonce,
            'CurTime:'. $this->CurTime,
            'CheckSum:'. $this->CheckSum,
            'Content-Type:application/x-www-form-urlencoded;charset=utf-8'
        );

        $post_data = array(
        	'accid'=>'zhangsan',
        );
        
        // $str = implode('',$header);
        // file_put_contents('params.log', $str."\n----------\n", FILE_APPEND);
        // $header['CheckSum'] = sha1($str);
        // $header['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
        file_put_contents('params.log', $this->CurTime."\n-----\n".print_r($http_header, true)."\n====================\n", FILE_APPEND);
        
       	// $data['accid'] = 'zhangsan';
       	
       	$res = $this->cUrl_post($post_data, $url, $http_header);
       	file_put_contents('res.log',print_r($res, true)."\n", FILE_APPEND);
    }


    /**
     * 创建云信ID
     * 1.第三方帐号导入到云信平台；
     * 2.注意accid，name长度以及考虑管理秘钥token
     * @param  $accid     [云信ID，最大长度32字节，必须保证一个APP内唯一（只允许字母、数字、半角下划线_、@、半角点以及半角-组成，不区分大小写，会统一小写处理）]
     * @param  $name      [云信ID昵称，最大长度64字节，用来PUSH推送时显示的昵称]
     * @param  $props     [json属性，第三方可选填，最大长度1024字节]
     * @param  $icon      [云信ID头像URL，第三方可选填，最大长度1024]
     * @param  $token     [云信ID可以指定登录token值，最大长度128字节，并更新，如果未指定，会自动生成token，并在创建成功后返回]
     * @return $result    [返回array数组对象]
     */
    // public function createUserId($accid,$name='',$props='{}',$icon='',$token=''){
    //     $url = 'https://api.netease.im/nimserver/user/create.action';
    //     $data= array(
    //         'accid' => $accid,
    //         'name'  => $name,
    //         'props' => $props,
    //         'icon'  => $icon,
    //         'token' => $token
    //     );
    //     if($this->RequestType=='curl'){
    //         $result = $this->postDataCurl($url,$data);
    //     }else{
    //         $result = $this->postDataFsockopen($url,$data);
    //     }
    //     return $result;
    // }


    private function checkSumBuilder()
    {
    	$this->Nonce = $this->getNonceStr();
    	$this->CurTime = time(); //当前时间戳，以秒为单位
    	// file_put_contents('time.log', $this->CurTime."\n------\n", FILE_APPEND);
    	$str = $this->AppKey.$this->Nonce.$this->CurTime;
    	$this->CheckSum = sha1($str);
    }


    /**
	 * 
	 * 产生随机字符串，不长于32位
	 * @param int $length
	 * @return 产生的随机字符串
	 */
	public function getNonceStr($length = 32) 
	{
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";  
		$str ="";
		for ( $i = 0; $i < $length; $i++ )  {  
			$str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
		} 
		return $str;
	}

	public function cUrl_post($data,$url,$header=array())
	{
		$ch = curl_init ();
	    if(count($header) >0)
	    {
	        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	    }

	    if(stripos($url, "https://") !== FALSE)
		{
			curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE);
			curl_setopt ( $ch, CURLOPT_SSLVERSION, 1);
		}

	    curl_setopt ( $ch, CURLOPT_URL,$url);
	    curl_setopt ( $ch, CURLOPT_POST, 1 );
	    curl_setopt ( $ch, CURLOPT_HEADER, 0 );
	    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
	    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data);
	    curl_setopt ( $ch, CURLOPT_TIMEOUT,15);//设置超时时间
	    $result = curl_exec ( $ch );
	    curl_close ( $ch );
	    //返回数组
	    return $result;
	}

	/**
	 * post json数据
	 */
	// public function cUrl_post_json($data,$url)
	// {
	//     return $this->cUrl_post($data,$url,
	//         array(
	//             'Content-Type: application/x-www-form-urlencoded;charset=utf-8',
	//             'Content-Length:'.strlen($data)
	//         )
	//     );
	// }
}